﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using CrystalDecisions.Shared;
using Microsoft.Win32;
using XBoshiGFS.forms;
using CrystalDecisions.CrystalReports.Engine;



namespace XBoshiGFS.reports
{
    public partial class WaterUsageBillsForm : Form
    {
        XBoshiGFSModelContainer context = new XBoshiGFSModelContainer();
        IQueryable  orgSql;
        String strGroupID;
        IList<WaterUsageBillsReportData> printDataList = new List<WaterUsageBillsReportData>();
        String strUserName = "";

        String strfcp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "firstCorrectPages", "");
        String strscp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "secondCorrectPages", "");
        String strrpp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "recordPerPages", "");
        String strprint = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "billPrinter", "");
        String bill1Height = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Height", "0");
        String bill1Width = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Width", "0");

        public WaterUsageBillsForm()
        {
            InitializeComponent();

            cmbStation.DataSource = (from p in context.StationSet select p);

            //灌季
            cmbWaterSeason.DataSource = (from p in context.WaterSeasonSet orderby p.strYear descending ,p.strSeason descending  select p);

            var strUserName = (from p in context.UsersSet where p.strCode == MainMDIParent.currentUserCode select p.strName).FirstOrDefault();

            WaterUsageBills1.SetParameterValue("IsPrint", true);


            //this.dataGridView1.DataSource = printDataList;
            //for (int i = this.dataGridView1.Columns.Count - 1; i > 1; i--)
            //{
            //    this.dataGridView1.Columns.Remove(this.dataGridView1.Columns[i]);
            //}
            //this.dataGridView1.Columns[0].DataPropertyName = "isPrint";
            //this.dataGridView1.Columns[1].DataPropertyName = "strPeopleName";

        }

        private void settingPrinter() {
            String strfcp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "firstCorrectPages", "");
            String strscp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "secondCorrectPages", "");
            String strrpp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "recordPerPages", "");
            String strprint = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "billPrinter", "");
            String bill1Height = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Height", "0");
            String bill1Width = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Width", "0");
            String bill1Left = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginLeft", "0");
            String bill1Top = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginTop", "0");
            String bill1Right = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginRight", "0");
            String bill1Bottom = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginBottom", "0");

            int iBill1Height = (int)(double.Parse(bill1Height) * 0.0393700787401575 * 100);
            int iBill1Width = (int)(double.Parse(bill1Width) * 0.0393700787401575 * 100);
            int iBill1Left = (int)(double.Parse(bill1Left) * 0.0393700787401575 * 100);
            int iBill1Top = (int)(double.Parse(bill1Top) * 0.0393700787401575 * 100);
            int iBill1Right = (int)(double.Parse(bill1Right) * 0.0393700787401575 * 100);
            int iBill1Bottom = (int)(double.Parse(bill1Bottom) * 0.0393700787401575 * 100);

            WaterUsageBills1.PrintOptions.PrinterName = strprint;
            System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
            ps.PrinterName = strprint;
            ps.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("billReport", iBill1Width, iBill1Height);
            ps.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(iBill1Left, iBill1Right, iBill1Top, iBill1Bottom);
            WaterUsageBills1.PrintOptions.CopyFrom(ps, ps.DefaultPageSettings);
            WaterUsageBills1.PrintOptions.PrinterName =strprint ;


        }



        private void crystalReportViewer1_Load(object sender, EventArgs e)
        {
                strGroupID = "-1";
                 try
                {
                 //orgSql = 
                 //            from  t in context.PeopleSet
                 //            join o in context.GroupSet on t.GroupId equals o.Id  
                 //            join p in context.VillageSet on o.VillageId equals p.Id
                 //            join q in context.WaterCourseSet on p.WaterCourseId equals q.Id
                 //            join r in context.SegmentCourseSet on q.SegmentCourseId equals r.Id
                 //            join s in context.StationSet on r.StationId equals s.Id
                 //            where p.Id == this.strGroupID
                 //            select new  {
                 //                t.strCode, t.strName ,
                 //                strGropId =p.Id,strGroupName =p.strName ,strGroupCode =p.strCode ,
                 //                strVillageCode =o.strCode ,strVillageName =o.strName ,
                 //                strWaterCourseCode =q.strCode ,strWaterCourseName  =q.strName ,
                 //                strSegmentCode =r.strCode ,strSegmentName =r.strName ,
                 //                strStationCode =s.strCode ,strStationName=s.strName 
                 //             };

                 //var orgSql = GetQuerySql("-1");

                   // ReportClientDocument doc = new ReportClientDocument();
                     
                    //doc.Open(WaterUsageBills1);
                      
                         
                  //  doc.Save(); 
                    
                     //using (ReportDocument rpt=new ReportDocument() ){
                     //    rpt.FileName = "reports/WaterUsageBills.rpt";
                     //    rpt.Load("reports/WaterUsageBills.rpt");
                     //    rpt.ReportDefinition; 
                     //}

                    for (var i = 0; i < 10; i++)
                    {
                        WaterUsageBillsReportData wprd = new WaterUsageBillsReportData();
                        wprd.strStationName = "test" + i;
                        wprd.strPeopleName  = "测试用户" + i;
                        printDataList.Add(wprd);
                    }
                    WaterUsageBills1.SetDataSource(printDataList);
                    WaterUsageBills1.SetParameterValue("IsPrint", true);

                     settingPrinter();//设置打印参数
                     WaterUsageBills1.Refresh();
                     dealGridView(); 



                }
                catch (Exception ex) {

                    var a = ex.InnerException;
                } 
        }


        private void cmbStation_SelectedIndexChanged(object sender, EventArgs e)
        {
            var strID = ((ComboBox)sender).SelectedValue;
            cmbSegment.DataSource = (from p in context.SegmentCourseSet where p.StationId == strID orderby p.strName select p);
        }

        private void cmbSegment_SelectedIndexChanged(object sender, EventArgs e)
        {
            var strID = ((ComboBox)sender).SelectedValue;
            cmbWaterCourse.DataSource = (from p in context.WaterCourseSet where p.SegmentCourseId == strID orderby p.strName select p);

        }

        private void cmbWaterCourse_SelectedIndexChanged(object sender, EventArgs e)
        {
            var strID = ((ComboBox)sender).SelectedValue;
            cmbVillage.DataSource = (from p in context.VillageSet where p.WaterCourseId == strID orderby p.strName select p);

        }

        private void cmbVillage_SelectedIndexChanged(object sender, EventArgs e)
        {
            var strID = ((ComboBox)sender).SelectedValue;
            cmbGroup.DataSource = (from p in context.GroupSet where p.VillageId == strID orderby p.strName select p);

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            printDataList.Clear();

            try
            {
                WaterUsageBills1.ReportDefinition.ReportObjects["Picture2"].ObjectFormat.EnableSuppress = false;


                this.Cursor = Cursors.WaitCursor;   
                strGroupID = (String)cmbGroup.SelectedValue;
              //形成打印数据
                var sql = GetQuerySql(strGroupID);
                crystalReportViewer1.ReportSource = WaterUsageBills1; 
                WaterUsageBills1.SetDataSource(printDataList);
                WaterUsageBills1.SetParameterValue("IsPrint", true);
                settingPrinter();//设置打印参数


                WaterUsageBills1.Refresh();
                
                //crystalReportViewer1.RefreshReport();     


            }catch(Exception ex){
            
            }
            this.Cursor = Cursors.Default ;   
        }

        private IQueryable GetQuerySql(String strGroupID)
        {
            String strSeasonID="";
            String feeID = "";
            try
            {
                  WaterSeasonSet season = ((WaterSeasonSet)(cmbWaterSeason.SelectedItem));
                  //SeasonName = season.strName;
                  strSeasonID = season.Id;
                  feeID = season.FeeStandardSetId;
                 // PriceAll = String.Format("{0}", (from p in context.FeeStandardSet where p.Id == season.FeeStandardSetId select p.PriceAll).FirstOrDefault());
            }
            catch { 
            
            
            }

            //printDataList.Clear();
            //this.dataGridView1.DataSource = printDataList;
            
            var orgSql =
            from u in context.WaterUsageSet 
            join t in context.PeopleSet on  u.PeopleId  equals t.Id 
            join o in context.GroupSet on t.GroupId equals o.Id
            join p in context.VillageSet on o.VillageId equals p.Id
            join q in context.WaterCourseSet on p.WaterCourseId equals q.Id
            join r in context.SegmentCourseSet on q.SegmentCourseId equals r.Id
            join s in context.StationSet on r.StationId equals s.Id
            join fee in context.FeeStandardSet on u.FeeStandardId  equals fee.Id 
            join season in context.WaterSeasonSet on u.WaterSeasonId  equals season.Id 
            where o.Id == this.strGroupID  && season.Id == strSeasonID && u.FeePrintLogSet.Count <=0  && u.WaterCap >0
            orderby t.strCode 
            select new // WaterUsageBillsReportData 
            {
                strPeopleID = t.Id,
                strPeopleCode= t.strCode,
                strPeopleName=t.strName,
                strGropId = p.Id,
                strGroupName = o.strName,
                strGroupCode = o.strCode,
                strVillageCode = p.strCode,
                strVillageName = p.strName,
                strWaterCourseCode = q.strCode,
                strWaterCourseName = q.strName,
                strSegmentCode = r.strCode,
                strSegmentName = r.strName,
                strStationCode = s.strCode,
                strStationName = s.strName,
                strGroupManager = o.strManager,
                strWaterSeasonName =season.strName,
                strFeeStardName =fee.strName ,
                decUseArea =u.UseArea.Value  ,
                decWaterBill =u.WaterBill.Value ,
                decWaterCap =u.WaterCap.Value  ,
                decReceivedBill =u.WaterBill.Value  ,
                decFlowRate =u.FlowRate.Value ,
                decPriceAll =fee.PriceAll.Value ,
                decRemain =0.0M,
                intUseLong =u.UseLong.Value ,
                datBeginTime = u.BeginTime==null?DateTime.Now:u.BeginTime.Value,
                strWaterUsageID=u.Id 
            };

           foreach (var wub in orgSql) {
               WaterUsageBillsReportData tmp = new WaterUsageBillsReportData
               {
                   strPeopleID = wub.strPeopleID,
                   strPeopleCode = wub.strPeopleCode,
                   strPeopleName = wub.strPeopleName,
                   strGropId = wub.strGropId,
                   strGroupName = wub.strGroupName,
                   strGroupCode = wub.strGroupCode,
                   strVillageCode = wub.strVillageCode,
                   strVillageName = wub.strVillageName,
                   strWaterCourseCode = wub.strWaterCourseCode,
                   strWaterCourseName = wub.strWaterCourseName,
                   strSegmentCode = wub.strSegmentCode,
                   strSegmentName = wub.strSegmentName,
                   strStationCode = wub.strStationCode,
                   strStationName = wub.strStationName,
                   strGroupManager = wub.strGroupManager,
                   strWaterSeasonName = wub.strWaterSeasonName,
                   strFeeStardName = wub.strFeeStardName,
                   decUseArea = wub.decUseArea,
                   decWaterBill = wub.decWaterBill,
                   decWaterCap = wub.decWaterCap,
                   decReceivedBill = wub.decReceivedBill,
                   decFlowRate = wub.decFlowRate,
                   decPriceAll = wub.decPriceAll,
                   decRemain = wub.decRemain,
                   intUseLong = wub.intUseLong,
                   datBeginTime = wub.datBeginTime,
                   strWaterUsageID = wub.strWaterUsageID,
                   isPrint =true  
                   
               };

               printDataList.Add(tmp);


                
           }
        //   this.dataGridView1.DataSource = null;
       //    this.dataGridView1.Rows.Clear(); 
           dealGridView();
           //this.dataGridView1.Refresh(); 


           return orgSql ;
        }


        private void dealGridView() {
            dataGridView1.DataSource = null;
            if (printDataList.Count > 0)
            {
                dataGridView1.Enabled = true;
                this.dataGridView1.DataSource = printDataList;
                for(int i=0;i<dataGridView1.Columns.Count;i++) {
                    if (dataGridView1.Columns[i].DataPropertyName == "isPrint")
                    {
                        dataGridView1.Columns[i].HeaderText = "打印";
                    }
                    else if (dataGridView1.Columns[i].DataPropertyName == "strPeopleName")
                    {
                        dataGridView1.Columns[i].HeaderText = "姓名";
                    }
                    else {

                        dataGridView1.Columns[i].Visible = false; 
                    }
                
                } 




            }
            else
            {
                dataGridView1.Enabled = false;
                dataGridView1.DataSource = null;
            }
            this.dataGridView1.Refresh();
            if (dataGridView1.Rows.Count > 0)
            {
                try
                {
                    dataGridView1.CurrentCell = this.dataGridView1.Rows[0].Cells[0];
                }
                catch { }
            }
        
        }


        private void cmbGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
    
        }

        private void cmbWaterSeason_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.btnQuery.Enabled = true;
        }

        private void WaterBillReportForm_Load(object sender, EventArgs e)
        {

        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }
        /// <summary>
        /// 调用直接打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 

        [DllImport("printDll.dll")]
        static extern void printBill(string msg); 
        private void btnPrintActiveObject(object sender, EventArgs e)
        {
            foreach (var wup in printDataList)
            {
                String strPrint = ""+getMessageString(wup);
                try
                {
                    printBill(strPrint);
                }catch(Exception ex){
                
                } 
            }

        }
        private void btnPrintActiveObjectByFile(object sender, EventArgs e)
        {
            FileStream f = File.Create("printData.tmp") ;
            StreamWriter sw = new StreamWriter(f);
            foreach (var wup in printDataList)
            {
                String strPrint = "" + getMessageString(wup);
                sw.WriteLine(strPrint);
            }
            sw.Close();
            f.Close();

            //调用打印文件
            Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = Application.StartupPath + "\\aa.bat";
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            process.StartInfo.Arguments = "printData.tmp";
            process.Start();
        }

        private String getMessageString(WaterUsageBillsReportData data) {
            String strRs = "";
            int i = 0;
            strRs = strRs + "省桃曲坡水库管理局|";
            strRs = strRs + data.strStationName  +"|";
           // strRs = strRs + data.strSegmentName  + "|";
            strRs = strRs + data.strWaterCourseName  + "|";
            strRs = strRs + data.strVillageName  + "|";
            strRs = strRs + data.strGroupName  + "|";
            strRs = strRs + data.strPeopleName + "|";
            strRs = strRs + data.strPeopleCode + "|";
            strRs = strRs + data.decUseArea + "|";


            strRs = strRs + data.datBeginTime.ToShortDateString()   + "|";

            strRs = strRs + data.strFeeStardName+ "|";
            strRs = strRs + data.decFlowRate  + "|";
            strRs = strRs + data.intUseLong  + "|";
            strRs = strRs + data.decWaterCap  + "|";

            strRs = strRs + data.decPriceAll + "|";
            strRs = strRs + data.decWaterBill + "|";
            strRs = strRs + data.decReceivedBill  + "|";
            strRs = strRs + data.decRemain  + "|";
            strRs = strRs + DateTime.Now.Year    + "|";
            strRs = strRs + DateTime.Now.Month + "|";
            strRs = strRs + DateTime.Now.Day + "|";





            return strRs;
        
        }
        private void a() {

            //System.Drawing.Printing.PrintDocument pDoc = new System.Drawing.Printing.PrintDocument();
            //CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions rasPROpts = new CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions();

            //CrystalDecisions.ReportAppServer.ReportDefModel.PrintOptions MYPRTOpts = new CrystalDecisions.ReportAppServer.ReportDefModel.PrintOptions();
            //if (rdoCurrent.Checked)
            //{
            //    pDoc.PrinterSettings.PrinterName = cboCurrentPrinters.Text;

            //    MYPRTOpts.PrinterName = cboCurrentPrinters.Text;
            //    MYPRTOpts.PaperSize = (CrPaperSizeEnum)
            //           pDoc.PrinterSettings.PaperSizes[cboCurrentPaperSizes.SelectedIndex].Kind;
            //    MYPRTOpts.PaperSource = (CrPaperSourceEnum)
            //           pDoc.PrinterSettings.PaperSources[cboCurrentPaperTrays.SelectedIndex].Kind;
            //    // added the below line to verify the changes work.
            //    MYPRTOpts.PaperOrientation = CrPaperOrientationEnum.crPaperOrientationLandscape;
            //}
            //else
            //{
            //    pDoc.PrinterSettings.PrinterName = cboDefaultPrinters.Text;

            //    MYPRTOpts.PrinterName = cboDefaultPrinters.Text;
            //    MYPRTOpts.PaperSize = (CrPaperSizeEnum)
            //           pDoc.PrinterSettings.PaperSizes[cboDefaultPaperSizes.SelectedIndex].Kind;
            //    MYPRTOpts.PaperSource = (CrPaperSourceEnum)
            //           pDoc.PrinterSettings.PaperSources[cboDefaultPaperTrays.SelectedIndex].Kind;
            //}
            //rptClientDoc.PrintOutputController.ModifyPrintOptions(MYPRTOpts);
            //MessageBox.Show("Printer set.", "RAS", MessageBoxButtons.OK, MessageBoxIcon.Information);

            //rptClientDoc.PrintOutputController.PrintReport(rasPROpts);
            //MessageBox.Show("Printing report.", "RAS", MessageBoxButtons.OK, MessageBoxIcon.Information); 


        
        }


        private void btnPrintCrystalReportObject(object sender, EventArgs e)
        {
            //使用报表定义，一次打出所有数据
            String strfcp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "firstCorrectPages", "");
            String strscp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "secondCorrectPages", "");
            String strrpp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "recordPerPages", "");
            String strprint = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "billPrinter", "");
            String bill1Height = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Height", "0");
            String bill1Width = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Width", "0");
            String bill1Left = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginLeft", "0");
            String bill1Top = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginTop", "0");
            String bill1Right = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginRight", "0");
            String bill1Bottom = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginBottom", "0");

            int iBill1Height = (int)(double.Parse(bill1Height) * 0.0393700787401575 * 100);
            int iBill1Width = (int)(double.Parse(bill1Width) * 0.0393700787401575 * 100);
            int iBill1Left = (int)(double.Parse(bill1Left) * 0.0393700787401575 * 100);
            int iBill1Top = (int)(double.Parse(bill1Top) * 0.0393700787401575 * 100);
            int iBill1Right = (int)(double.Parse(bill1Right) * 0.0393700787401575 * 100);
            int iBill1Bottom = (int)(double.Parse(bill1Bottom) * 0.0393700787401575 * 100);
            WaterUsageBills1.PrintOptions.PrinterName = strprint;
            System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
            ps.PrinterName = strprint;
            ps.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("billReport", iBill1Width, iBill1Height);
            ps.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(iBill1Left, iBill1Right, iBill1Top, iBill1Bottom);
            WaterUsageBills1.PrintOptions.CopyFrom(ps, ps.DefaultPageSettings);
            WaterUsageBills1.PrintOptions.PrinterName = strprint;
            
            WaterUsageBills1.PrintToPrinter(ps, ps.DefaultPageSettings, true);
        }
        private void btnPrintCrystalReportUsingModifyObject(object sender, EventArgs e)
        {
            //通过调整纸张大小的方式，来打印
            int firstCorrectPages = 1;
            int secondCorrectPages = 1000;
            int recordPerPage = 1;
            System.Drawing.Printing.PrintDocument doc = new System.Drawing.Printing.PrintDocument();
            int rawKind = 1; //记录标识自定义纸张的ID
            int paper1 = 0, paper2 = 0;
            //枚举出所有的打印纸尺寸 
            foreach (System.Drawing.Printing.PaperSize paper in doc.PrinterSettings.PaperSizes)
            {

                if (paper.PaperName.ToUpper().Equals("billReport".ToUpper() ))
                {
                    paper1 = paper.RawKind;
                    if (paper2 == 0) {
                        paper2 = paper1;
                    }
                }
                if (paper.PaperName.ToUpper() .Equals("billReport1".ToUpper()))
                {
                    paper2 = paper.RawKind;
                }
            }


            String strfcp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "firstCorrectPages", "");
            if (String.IsNullOrWhiteSpace(strfcp)) {
                strfcp = "1";
                Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "firstCorrectPages", strfcp);
            }
            String strscp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "secondCorrectPages", "");
            if (String.IsNullOrWhiteSpace(strscp))
            {
                strscp = "1000";
                Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "secondCorrectPages", strscp);
            }

            String strrpp = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "recordPerPages", "");
            if (String.IsNullOrWhiteSpace(strrpp))
            {
                strrpp = "1";
                Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "recordPerPages", strrpp);
            }

            String strprint = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "billPrinter", "");
            if (String.IsNullOrWhiteSpace(strprint))
            {
                strprint = doc.PrinterSettings.PrinterName;
                Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "recordPerPages", strprint);
            }
            firstCorrectPages =  Int32.Parse(strfcp);
            secondCorrectPages = Int32.Parse(strscp);
            recordPerPage = Int32.Parse(strrpp);



            String bill1Height = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Height", "0");
            String bill1Width = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1Width", "0");
            String bill2Height = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill2Height", "0");
            String bill2Width = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill2Width", "0");
            String bill1Left = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginLeft", "0");
            String bill1Top = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginTop", "0");
            String bill1Right = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginRight", "0");
            String bill1Bottom = (String)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "bill1MarginBottom", "0");
            
            int iBill1Height = (int)(double.Parse(bill1Height) * 0.0393700787401575  * 100);
            int iBill1Width = (int)(double.Parse(bill1Width) * 0.0393700787401575  * 100);
            int iBill2Height = (int)(double.Parse(bill2Height) * 0.0393700787401575  * 100);
            int iBill2Width = (int)(double.Parse(bill2Width) * 0.0393700787401575 * 100);

            int iBill1Left = (int)(double.Parse(bill1Left) * 0.0393700787401575 * 100);
            int iBill1Top = (int)(double.Parse(bill1Top) * 0.0393700787401575 * 100);
            int iBill2Left = (int)(double.Parse(bill1Left) * 0.0393700787401575 * 100);
            int iBill2Top = (int)(double.Parse(bill1Top) * 0.0393700787401575 * 100);

            int iBill1Right = (int)(double.Parse(bill1Right) * 0.0393700787401575 * 100);
            int iBill1Bottom = (int)(double.Parse(bill1Bottom) * 0.0393700787401575 * 100);
            int iBill2Right = (int)(double.Parse(bill1Right) * 0.0393700787401575 * 100);
            int iBill2Bottom = (int)(double.Parse(bill1Bottom) * 0.0393700787401575 * 100);

            //设置打印参数
             
            //修正纸张
            try
            {
                    WaterUsageBills1.SetDataSource(printDataList.Take(firstCorrectPages * recordPerPage).ToList());//设置打印的数据
                    WaterUsageBills1.Refresh();
                    System.Threading.Thread.Sleep(1000);    
 
                    System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
                    ps.PrinterName = strprint;
                    ps.FromPage = 1;
                    ps.ToPage = firstCorrectPages;
                    ps.Copies = 1;

                    System.Drawing.Printing.PageSettings page = new System.Drawing.Printing.PageSettings();
                    page.PaperSize = new System.Drawing.Printing.PaperSize("billReport", iBill1Width, iBill1Height);
                    page.Margins = new System.Drawing.Printing.Margins(iBill1Left, iBill1Right, iBill1Top, iBill1Bottom);
                    WaterUsageBills1.PrintOptions.CopyFrom(ps, page);
                    WaterUsageBills1.PrintOptions.PrinterName = strprint;
                    WaterUsageBills1.PrintToPrinter(ps, page, true);
                
            }
            catch(Exception ex) {
                System.Diagnostics.Debug.Print(ex.StackTrace);    
            }
     ;

            try
            {

                WaterUsageBills1.SetDataSource(printDataList.Skip(firstCorrectPages * recordPerPage).Take(recordPerPage).ToList());//设置打印的数据
                WaterUsageBills1.Refresh();
                System.Threading.Thread.Sleep(1000);

                System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
                ps.PrinterName = strprint;
                ps.FromPage = firstCorrectPages + 1;
                ps.ToPage = firstCorrectPages+1;
                ps.Copies = 1;

                System.Drawing.Printing.PageSettings page = new System.Drawing.Printing.PageSettings();
                page.PaperSize = new System.Drawing.Printing.PaperSize("billReport1", iBill2Width, iBill2Height);
                page.Margins = new System.Drawing.Printing.Margins(iBill2Left, iBill2Right, iBill2Top, iBill2Bottom);
                WaterUsageBills1.PrintOptions.CopyFrom(ps, page);
                WaterUsageBills1.PrintOptions.PrinterName = strprint;
                WaterUsageBills1.PrintToPrinter(ps, page, true);
                
                
                
                //WaterUsageBills1.PrintToPrinter(1, true, firstCorrectPages + 1, firstCorrectPages + 1);


            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print(ex.StackTrace);
            }

            int pages = (int)Math.Ceiling((double)(printDataList.Count / recordPerPage));


            for (var i = firstCorrectPages + 2; i <= pages; i = i + secondCorrectPages)
            {
                try
                {

                    ////正常纸张
                    WaterUsageBills1.SetDataSource(printDataList.Skip((i - 1) * recordPerPage).Take(secondCorrectPages * recordPerPage));//设置打印的数据

                    WaterUsageBills1.Refresh();
                    System.Threading.Thread.Sleep(1000);

                    System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
                    ps.PrinterName = strprint;
                    ps.FromPage = i;
                    ps.ToPage = i + secondCorrectPages - 2;
                    ps.Copies = 1;

                    System.Drawing.Printing.PageSettings page = new System.Drawing.Printing.PageSettings();
                    page.PaperSize = new System.Drawing.Printing.PaperSize("billReport", iBill1Width, iBill1Height);
                    page.Margins = new System.Drawing.Printing.Margins(iBill1Left, iBill1Right, iBill1Top, iBill1Bottom);
                    WaterUsageBills1.PrintOptions.CopyFrom(ps, page);
                    WaterUsageBills1.PrintOptions.PrinterName = strprint;
                    WaterUsageBills1.PrintToPrinter(ps, page, true);


                    if ((i + secondCorrectPages) * recordPerPage > printDataList.Count) {
                        break;
                    }
                    ////修正纸张
                    WaterUsageBills1.SetDataSource(printDataList.Skip((i + secondCorrectPages) * recordPerPage).Take(recordPerPage));//设置打印的数据
                    WaterUsageBills1.Refresh();
                    System.Threading.Thread.Sleep(1000);

                    System.Drawing.Printing.PrinterSettings ps1 = new System.Drawing.Printing.PrinterSettings();
                    ps1.PrinterName = strprint;
                    ps1.FromPage = i + secondCorrectPages - 1;
                    ps1.ToPage = i + secondCorrectPages - 1;
                    ps1.Copies = 1;
                    System.Drawing.Printing.PageSettings page1 = new System.Drawing.Printing.PageSettings();
                    page1.PaperSize = new System.Drawing.Printing.PaperSize("billReport1", iBill2Width, iBill2Height);
                    page1.Margins = new System.Drawing.Printing.Margins(iBill2Left, iBill2Right, iBill2Top, iBill2Bottom);
                    WaterUsageBills1.PrintToPrinter(ps1, page1, true);




                    ////正常纸张
                    //WaterUsageBills1.PrintOptions.PaperSize = (PaperSize)paper1;
                    //WaterUsageBills1.PrintToPrinter(1, true, i, i + secondCorrectPages - 2);
                    ////修正纸张
                    //WaterUsageBills1.PrintOptions.PaperSize = (PaperSize)paper2;
                    //WaterUsageBills1.PrintToPrinter(1, true, i + secondCorrectPages - 1, i + secondCorrectPages - 1);

                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Print(ex.Message);
                }
            }

        }


       /// <summary>
        /// 调用打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {

            WaterUsageBillsReportData[] backPrintDate = new WaterUsageBillsReportData[printDataList.Count]; 
            printDataList.CopyTo(backPrintDate, 0);

            for (int i = printDataList.Count-1; i > 0; i--)
            {
                var a = printDataList[i];
                if (a.isPrint == false)
                {
                    printDataList.Remove(a);
                }
            } 
            
            
            WaterUsageBills1.SetDataSource(printDataList);
            WaterUsageBills1.SetParameterValue("IsPrint", false);

            WaterUsageBills1.ReportDefinition.ReportObjects["Picture2"].ObjectFormat.EnableSuppress = true;



            String strPrintType =(String) Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Xboshi\\XBoshiGFS", "printType", "1");
            if (strPrintType.Equals("1")) { 
               //方式1，直接打印
                btnPrintCrystalReportObject(sender, e);
            }
            else if (strPrintType.Equals("2"))
            {
                //方式2，修正打印
                btnPrintCrystalReportUsingModifyObject(sender, e); 
            }
            else if (strPrintType.Equals("3"))
            {
                //方式3，DLL控件打印
                btnPrintActiveObjectByFile(sender, e); 
            }


            if (MessageBox.Show("是否全部正确打印？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                //这里记录打印的结果
                foreach (var wup in printDataList)
                {
                    if (wup.isPrint)
                    {
                        FeePrintLogSet fpl = new FeePrintLogSet();
                        fpl.Id = Guid.NewGuid().ToString();
                        fpl.WaterUsageId = wup.strWaterUsageID;
                        fpl.PrintTime = DateTime.Now;
                        fpl.strPrinter = strUserName;
                        context.AddToFeePrintLogSet(fpl);
                    }
                }
                context.SaveChanges();

                //重新查询
                btnQuery_Click(null, null);


            }
            else
            {

                return;
            }



        
        }

        private void dataGridView1_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {

            if (dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "isPrint") { 
                //打印选择按钮
                foreach (var p in printDataList) {
                    p.isPrint = !p.isPrint; 
                } 
            }

        }


    }
}
